package com.wechatnotice.wechatnotice.utils;

import lombok.RequiredArgsConstructor;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.core.io.ClassPathResource;
import org.springframework.core.io.Resource;
import org.springframework.mail.SimpleMailMessage;
import org.springframework.mail.javamail.JavaMailSender;
import org.springframework.mail.javamail.MimeMessageHelper;
import org.springframework.stereotype.Component;

import javax.mail.MessagingException;
import javax.mail.internet.MimeMessage;
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.text.MessageFormat;
import java.util.Date;

/**
 * <p>
 *
 * </p>
 *
 * @program: WechatNotice
 * @author: daPangDong
 * @create: 2022-11-15 09:44
 */
@Component
@RequiredArgsConstructor
public class SendMailClient {

    /**
     * 来源
     */
    @Value("${spring.mail.username}")
    private String from;

    private final JavaMailSender javaMailSender;

    /**
     * 发送验证码
     * @param mail 发送
     * @return 发送状态
     */
    public String getMailCode(String mail){
        int code = (int) ((Math.random() * 9 + 1) * 100000);
        //邮件设置1：一个简单的邮件
        SimpleMailMessage message = new SimpleMailMessage();
        message.setSubject("验证码消息");
        message.setText("您的验证码为 : 【 "+code+" 】");

        message.setFrom(from);
        message.setTo(mail);
        javaMailSender.send(message);
        return code+"";
    }

    public boolean sendMail(String email, String subject, String text) {
        MimeMessage mimeMessage = javaMailSender.createMimeMessage();
        try {
            MimeMessageHelper mimeMessageHelper = new MimeMessageHelper(mimeMessage, true);
            // 设置发件人
            mimeMessageHelper.setFrom(from);
            // 设置收件人
            mimeMessageHelper.setTo(email);
            // 设置邮件主题
            mimeMessageHelper.setSubject(subject);
            // 设置发送的文本信息
            mimeMessageHelper.setText(text);
            javaMailSender.send(mimeMessage);
            return true;
        } catch (MessagingException e) {
            e.printStackTrace();
            return false;
        }
    }

    /**
     * 发送html邮件
     * @param email
     * @param subject
     * @return
     */
    public boolean sendHtmlToMail(String email, String subject){
        MimeMessage mimeMessage = javaMailSender.createMimeMessage();
        try {
            MimeMessageHelper helper = new MimeMessageHelper(mimeMessage, true);

            //获取验证码
            int randomCode = (int) ((Math.random() * 9 + 1) * 100000);

            String text = buildContent(randomCode+"");

            helper.setSentDate(new Date());
            helper.setFrom(from);
            helper.setTo(email);
            helper.setSubject(subject);
            //注意此处，sendText是个重载函数，也可以不带后面这个参数，为true时表示发送html格式的邮件，
            // 为false是为文本模式的邮件，默认为false，也就是文本模式的邮件，最开始就是没注意这一点儿导致发送出去的html格式的邮件全都显示不出来
            helper.setText(text,true);

            javaMailSender.send(mimeMessage);
            return true;
        } catch (MessagingException e) {
            e.printStackTrace();
            return false;
        }

    }

    /**
     * 读取邮件模板
     * 替换模板中的信息
     *
     * @param title 内容
     * @return html信息
     */
    public String buildContent(String title) {
        //加载邮件html模板
        Resource resource = new ClassPathResource("templates/ftl/mail.ftl");
        InputStream inputStream = null;
        BufferedReader fileReader = null;
        StringBuilder buffer = new StringBuilder();
        String line;
        try {
            inputStream = resource.getInputStream();
            fileReader = new BufferedReader(new InputStreamReader(inputStream));
            while ((line = fileReader.readLine()) != null) {
                buffer.append(line);
            }
        } catch (Exception e) {
            System.out.printf("发送邮件读取模板失败{}", e);
        } finally {
            if (fileReader != null) {
                try {
                    fileReader.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
            if (inputStream != null) {
                try {
                    inputStream.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
        }
        //替换html模板中的参数
        return MessageFormat.format(buffer.toString(), title);
    }



}
